import React, { useState, PureComponent } from 'react';
import { connect, Dispatch } from 'umi';
import { UploadOutlined } from '@ant-design/icons';
import { Layout, Tree, Spin, Row, Col, Button, Upload, Form } from 'antd';
import { RcFile } from 'antd/lib/upload';
import { isEmpty } from 'lodash';
import PdfViewer from '@/components/PdfViewer';
import { StateType } from './model';

interface UploadPdfProps {
  value?: RcFile;
  onChange?: (value?: RcFile) => void;
}

const UploadPdf: React.FC<UploadPdfProps> = ({ value, onChange }) => {
  const [fs, setFileList] = useState(value ? [value] : []);

  return (
    <Upload
      action="http://192.168.0.107:8080/tsapi/file/upload"
      name="file"
      accept=".pdf"
      fileList={fs}
      onRemove={() => {
        setFileList([]);
        if (onChange) {
          onChange(undefined);
        }
      }}
      beforeUpload={(file) => {
        setFileList([file]);
        if (onChange) {
          onChange(file);
        }
        return false;
      }}
    >
      <Button disabled={fs.length > 0} size="small" title="上传">
        <UploadOutlined /> 点击上传
      </Button>
    </Upload>
  );
};

const { Content, Sider, Header } = Layout;

interface BasicProps {
  match: any;
  pdfCompare: StateType;
  dispatch: Dispatch;
  comparing: boolean;
  uploading: boolean;
  treeData: any[];
}

interface BasicState {
  autoExpandParent: boolean;
  selectedKeys: string[];
  mPage: number;
  oPage: number;
  mRef: any;
  oRef: any;
  scale: number;
}

class CompareResult extends PureComponent<BasicProps, BasicState> {
  state = {
    autoExpandParent: true,
    selectedKeys: [],
    mPage: 0,
    oPage: 0,
    mRef: null,
    oRef: null,
    scale: 1,
  };

  componentDidMount() {}

  handleSelect = (selectedKeys: any, e: any) => {
    this.setState({
      selectedKeys,
    });
    const { node, selected } = e;
    if (selected) {
      const {
        type,
        data: { mPage, oPage, page },
      } = node;
      switch (type) {
        case 'diff':
          this.setState({
            mPage,
            oPage,
          });
          break;
        case 'miss':
        case 'increas':
          this.setState({
            mPage: page,
            oPage: page,
          });
          break;
        default:
          break;
      }
    }
  };

  handleDrawComplete = () => {};

  handleSetMRef = (ref: any) => {
    this.setState({
      mRef: ref,
    });
  };

  handleSetORef = (ref: any) => {
    this.setState({
      oRef: ref,
    });
  };

  handleScroll = (left: number, top: number) => {
    const { mRef, oRef } = this.state;
    if (mRef) {
      mRef.scrollLeft = left;
      mRef.scrollTop = top;
    }
    if (oRef) {
      oRef.scrollLeft = left;
      oRef.scrollTop = top;
    }
  };

  handleZoom = (scale: number) => {
    this.setState({
      scale,
    });
  };

  handlePageChange = (current: number) => {
    this.setState({
      oPage: current,
      mPage: current,
    });
  };

  handlePdfUpload = (mode: string, file?: RcFile) => {
    const { dispatch } = this.props;
    if (file) {
      dispatch({
        type: 'pdfCompare/uploadPdf',
        payload: {
          mode,
          file,
        },
      });
    } else if (mode === 'o') {
      dispatch({
        type: 'pdfCompare/save',
        payload: {
          oUrl: '',
          compareMarks: [[], []],
          treeData: [],
        },
      });
    } else if (mode === 'm') {
      dispatch({
        type: 'pdfCompare/save',
        payload: {
          mUrl: '',
          compareMarks: [[], []],
          treeData: [],
        },
      });
    }
  };

  render() {
    const { autoExpandParent, selectedKeys, mPage, oPage, scale } = this.state;
    const {
      dispatch,
      comparing,
      uploading,
      pdfCompare: { treeData, mUrl, oUrl, compareMarks },
    } = this.props;

    const formLayout = {
      labelCol: { xl: 4 },
      wrapperCol: { xl: 18 },
    };

    return (
      <Spin
        // eslint-disable-next-line no-nested-ternary
        tip={comparing ? '正在比对中' : uploading ? '上传中' : ''}
        spinning={comparing || uploading}
      >
        <Layout>
          <Header style={{ background: 'rgba(0, 0, 0, 0.12)' }}>
            <div>
              <Form
                {...formLayout}
                onFinish={() => {
                  dispatch({
                    type: 'pdfCompare/pdfCompare',
                  });
                }}
              >
                <Row gutter={24}>
                  <Col span={6}>
                    <Form.Item
                      name="oFile"
                      label="原图纸"
                      rules={[
                        {
                          required: true,
                          validator: (_, value) => {
                            const promise = Promise;
                            if (isEmpty(value)) {
                              return promise.reject('请选择文件');
                            }
                            return promise.resolve();
                          },
                          message: '请选择文件',
                        },
                      ]}
                    >
                      <UploadPdf
                        onChange={(file?: RcFile) => {
                          this.handlePdfUpload('o', file);
                        }}
                      />
                    </Form.Item>
                  </Col>
                  <Col span={6}>
                    <Form.Item
                      name="mFile"
                      label="新图纸"
                      rules={[
                        {
                          required: true,
                          validator: (_, value) => {
                            const promise = Promise;
                            if (isEmpty(value)) {
                              return promise.reject('请选择文件');
                            }
                            return promise.resolve();
                          },
                          message: '请选择文件',
                        },
                      ]}
                    >
                      <UploadPdf
                        onChange={(file?: RcFile) => {
                          this.handlePdfUpload('m', file);
                        }}
                      />
                    </Form.Item>
                  </Col>
                  <Col span={4}>
                    <Form.Item>
                      <Button size="large" type="primary" htmlType="submit">
                        比对
                      </Button>
                    </Form.Item>
                  </Col>
                </Row>
              </Form>
            </div>
          </Header>
          <Layout>
            <Sider theme="light" width={240} style={{ padding: 5 }}>
              <h1>比对结果</h1>
              <Tree
                showIcon
                showLine
                autoExpandParent={autoExpandParent}
                onSelect={this.handleSelect}
                selectedKeys={selectedKeys}
                treeData={treeData}
              />
            </Sider>
            <Content style={{ padding: '0 0 0 6px', minHeight: window.innerHeight - 64 }}>
              <Row gutter={16}>
                <Col span={12}>
                  {!isEmpty(oUrl) && (
                    <PdfViewer
                      scale={scale}
                      setRef={this.handleSetORef}
                      page={oPage}
                      canvasDivHeight={window.innerHeight - 100}
                      url={oUrl}
                      marks={compareMarks[1]}
                      markable={false}
                      onDrawComplete={this.handleDrawComplete}
                      onScroll={this.handleScroll}
                      onZoom={this.handleZoom}
                      onPageChange={this.handlePageChange}
                    />
                  )}
                </Col>
                <Col span={12}>
                  {!isEmpty(mUrl) && (
                    <PdfViewer
                      scale={scale}
                      setRef={this.handleSetMRef}
                      page={mPage}
                      canvasDivHeight={window.innerHeight - 100}
                      url={mUrl}
                      marks={compareMarks[0]}
                      markable={false}
                      onDrawComplete={this.handleDrawComplete}
                      onScroll={this.handleScroll}
                      onZoom={this.handleZoom}
                      onPageChange={this.handlePageChange}
                    />
                  )}
                </Col>
              </Row>
            </Content>
          </Layout>
        </Layout>
      </Spin>
    );
  }
}

export default connect(
  ({
    pdfCompare,
    loading,
  }: {
    pdfCompare: StateType;
    loading: {
      models: { [key: string]: boolean };
      effects: any;
    };
  }) => ({
    pdfCompare,
    comparing: loading.effects['pdfCompare/pdfCompare'] || false,
    uploading: loading.effects['pdfCompare/uploadPdf'] || false,
  }),
)(CompareResult);
